//
//  ZRLoginViewController.swift
//  Sina
//
//  Created by 张锐 on 16/2/26.
//  Copyright © 2016年 zhangr. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
class ZRLoginViewController: UIViewController ,UIWebViewDelegate{

    var webView :UIWebView?
    
    override func loadView() {
        
        //设置View
        webView = UIWebView(frame: UIScreen.mainScreen().bounds)
        //设置背景色
        webView!.backgroundColor = UIColor.whiteColor()
        //设置代理
        webView?.delegate = self
        
        view = webView
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavButtons()
        
        //调用getcode
        getCodeByAuthorizeFromOauth2()
       
    }

}
// MARK: - nav左右按钮
extension ZRLoginViewController{

    func setupNavButtons(){
    
        //设置nav的左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "backButtonClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillNameAndPassword")
    
    
    }
    /**
     返回按钮
     */
    func backButtonClick(){
    
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    /**
     自动填充
     */
    func fillNameAndPassword(){
    
//        document.getElementById("userId").value = "15114604266"
//        document.getElementById("passwd").value = "lashinidie123"
        //插入js代码
        let js = "document.getElementById(\"userId\").value = \"15114604266\";document.getElementById(\"passwd\").value = \"lashinidie123\""

        webView?.stringByEvaluatingJavaScriptFromString(js)
    
    }


}
// MARK: - getData
extension ZRLoginViewController{
    /**
     获得code
     */
    func getCodeByAuthorizeFromOauth2(){
    
//        https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
        //拼接URL
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPLE_KEY)&redirect_uri=\(BACK_URL)&response_type=code")
        //搞出请求
        let request = NSURLRequest(URL: url!)
        //加载页面
        webView?.loadRequest(request)
        
        
    
    }
}
// MARK: - webViewDelegate
extension ZRLoginViewController{
    /*
    *等待条
     */
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    /**
     加载完成弄掉等待条
     */
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    /**
     失败了也要搞掉等待条
     */
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    /**
     监听获取code
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        
        let urlStr = request.URL?.absoluteString
        
        if urlStr!.hasPrefix(BACK_URL) {
            
            //            第一种     "="号断开，取后面部分
            let Opcode =  urlStr!.componentsSeparatedByString("=").last
            
            //        第二种
            //            if let lastCode = request.URL?.query{
            //
            //                let code = lastCode.substringFromIndex("code=".endIndex)
            //
            //                print(code)
            //            }
            
            if let code = Opcode {
                
                //                            print(code)
                /**
                *  最后的成功才是成功，任何的失败都是失败
                */
               ZRTokenModelView().getTokenByAccess_tokenFromOauth2(code, success: { () -> () in
                
                
                SVProgressHUD.dismiss()
//                NSNotificationCenter.defaultCenter().postNotificationName("changeRootController", object: nil)
                
                self.presentViewController(ZRWelcomeViewController(), animated: false, completion: { () -> Void in
                    
                })
                
//                self.dismissViewControllerAnimated(true, completion: nil)
                
                
                    }, failure: { () -> () in
                        print("失败")
                })
            }
          
            
            return false
        }
        
        return true
        
    }
}
